import * as fs from "fs";
import * as path from "path";

const CONFIG_DIR = path.join(__dirname, "../../config");
const CONFIG_PATH = path.join(CONFIG_DIR, "userConfig.json");

interface TestAgentConfig {
  neo4j: {
    serverUrl: string;
    serverUser: string;
    serverPassword: string;
  };
  llm: {
    apiBase: string;
    apiKey: string;
    model: string;
  };
  environment: {
    JAVA_HOME: string;
  };
}

const defaultConfig: TestAgentConfig = {
  neo4j: {
    serverUrl: "",
    serverUser: "",
    serverPassword: "",
  },
  llm: {
    apiBase: "",
    apiKey: "",
    model: "deepseek-chat",
  },
  environment: {
    JAVA_HOME: "",
  },
};

export function getConfig(): TestAgentConfig {
  ensureConfigFile();
  const configData = fs.readFileSync(CONFIG_PATH, "utf8");
  try {
    return JSON.parse(configData) as TestAgentConfig;
  } catch (err) {
    throw new Error("Failed to parse configuration file.");
  }
}

export function setConfig(newConfig: TestAgentConfig): void {
  ensureConfigDir();
  const configData = JSON.stringify(newConfig, null, 2);
  fs.writeFileSync(CONFIG_PATH, configData, "utf8");
}

function ensureConfigFile(): void {
  ensureConfigDir();
  if (!fs.existsSync(CONFIG_PATH)) {
    const data = JSON.stringify(defaultConfig, null, 2);
    fs.writeFileSync(CONFIG_PATH, data, "utf8");
  }
}

function ensureConfigDir(): void {
  if (!fs.existsSync(CONFIG_DIR)) {
    fs.mkdirSync(CONFIG_DIR, { recursive: true });
  }
}
